﻿using Batman.Maintenance;
using Batman.Maintenance.DTO;
using Batman.Maintenance.DTO.InputDTO;
using Batman.Maintenance.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;

namespace Batman.Cms.Core.Controllers
{
    [AllowAnonymous]
    public class MaintenanceController : Controller
    {
        IServiceProvider _serviceProvider;

        public MaintenanceController(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public IActionResult Index()
        {
            var res = MaintenanceAdmin.Get();
            return Json(res);
        }

        /// <summary>
        /// 列表数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResponseBase Item(string id)
        {
            var item = MaintenanceAdmin.Get().FirstOrDefault(t => t.Id == id);
            if (item == null) return new ResponseBase(404, $"对象不存在,未配置:{id}");

            return new ResponseBase { Result = item };
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ResponseBase Read(ReadInputDTO input)
        {
            var id = input.Id;
            var page = input.page;

            var item = MaintenanceAdmin.Get().FirstOrDefault(t => t.Id == id);
            if (item == null) return new ResponseBase(404, $"对象不存在,未配置:{id},请确认识否调用：MaintenanceAdmin.Registe");

            var entityType = item.GetEntityType(); // 获取到对象类型

            var generic = typeof(MaintenanceRepository<>).MakeGenericType(new Type[] { entityType });

            var repo = _serviceProvider.GetService(generic);

            var result = generic.GetMethod("Gets").Invoke(repo, new object[] { input, item });

            return new ResponseBase { Result = result };
        }
    }
}
